package com.chinastock.model;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Objects;

/**
 * @author wangzhendong
 */
@Data
public class EcpMessage extends Message{
    private Throwable exception;
    private String url;

    public EcpMessage() {
    }

    public EcpMessage(Throwable exception) {
        this.exception = exception;
    }

    @Override
    public String toString() {
        StringBuilder content = new StringBuilder("[");
        if(Objects.nonNull(url)){
            content.append("url="+url+",");
        }
        if(Objects.nonNull(exception)){
            Throwable actual = exception;
            /**
             * 如果判断当前的exception是target，则使用cause
             */
            if(StringUtils.isBlank(exception.getMessage())){
                actual = Objects.isNull(exception.getCause())?exception:exception.getCause();
            }
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            actual.printStackTrace(printWriter);
            /*替换换行符*/
            printWriter.flush();
            String stackTrace = stringWriter.toString();
            /**
             * 替换掉换行符
             */
            if(Objects.nonNull(stackTrace)){
                stackTrace = stackTrace.replaceAll("\\n|\\r","|");
            }
            /**
             * 打印
             */
            content.append("exception="+stackTrace+",");
        }
        return content.toString();
    }
}
